package com.ogawa.chair7808.ui.presenter;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.util.Log;

import com.ogawa.chair7808.R;
import com.ogawa.chair7808.cache.GlobalCache;
import com.ogawa.chair7808.manager.DataManager;
import com.ogawa.chair7808.observer.SoftApNewModel;
import com.ogawa.chair7808.ui.iview.ISoftApNewView;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.ogawa.chair7808.observer.SoftApNewModel.ACTION_SUCCESS;
import static com.ogawa.chair7808.observer.SoftApNewModel.CONNECT_SOCKET_TIMEOUT;
import static com.ogawa.chair7808.observer.SoftApNewModel.ERROR_SOCKET_FAILED;
import static com.ogawa.chair7808.observer.SoftApNewModel.ERROR_SOCKET_NULL;
import static com.ogawa.chair7808.observer.SoftApNewModel.ERROR_SSID_NULL;
import static com.ogawa.chair7808.observer.SoftApNewModel.ERROR_SSID_WRONG;
import static com.ogawa.chair7808.observer.SoftApNewModel.ERROR_WIFI_DISABLED;
import static com.ogawa.chair7808.observer.SoftApNewModel.READ_SN_TIMEOUT;
import static com.ogawa.chair7808.observer.SoftApNewModel.SCAN_AP_TIMEOUT;

/**
 * 作者: bright.lin@medisana.net.cn
 * 时间: 2019/1/2
 * 标题: 配网Presenter层（8.0以上版本）
 * 描述: 配网功能Presenter层实现
 * 修改: 由 bright.lin@medisana.net.cn 修改于 2019/1/2
 */
public class SoftApNewPresenter {
    private final static String TAG = /*SoftApPresenter.class.getName()*/"TEST";

    // View层对象
    private ISoftApNewView mView;
    // Model层对象
    private SoftApNewModel softApModel;

    // 是否初始化
    private boolean isInit = false;
    // 是否已读取到设备的MAC地址
    private boolean getMac = false;
    // 是否配网成功标志位
    private boolean isSuccess = false;

    /**
     * 带参构造器
     * @param context 上下文
     * @param view View层对象
     */
    public SoftApNewPresenter(Context context, ISoftApNewView view) {
        this.mView = view;
        softApModel = new SoftApNewModel(context);
    }

    /**
     * 释放资源
     */
    public void onDestroy() {
        softApModel.onDestroy();
    }

    /**
     * 初始化
     */
    public void init() {
        mView.setSettingFlag();
        mView.showDialog(R.string.softap_tip1_connect_chair, R.string.softap_tip3_connect_chair);
    }

    /**
     * 刷新WIFI按钮响应
     */
    public void scan() {
        mView.showWaiting();
        Observable.create(this::startScan)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    Disposable d;

                    @Override
                    public void onSubscribe(Disposable d) {
                        this.d = d;
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mView.dismissWaiting();
                        if (integer == ACTION_SUCCESS) {
                            mView.onWifiList(softApModel.getWifiResults());
                        } else {
                            handleScanFailue(integer);
                        }
                        d.dispose();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissWaiting();
                        d.dispose();
                    }

                    @Override
                    public void onComplete() {
                        mView.dismissWaiting();
                        d.dispose();
                    }
                });
    }

    /**
     * 开始扫描WIFI
     * @param emitter 事件发射器
     */
    private void startScan(ObservableEmitter<Integer> emitter) {
        softApModel.startScan(new SoftApNewModel.ScanApListener() {
            @Override
            public void onSuccess() {
                emitter.onNext(ACTION_SUCCESS);
                Log.d(TAG, "startScan emitter onSuccess");
            }

            @Override
            public void onFailure(int errorCode) {
                emitter.onNext(errorCode);
                Log.d(TAG, "startScan emitter onFailure");
            }
        });
        Log.d(TAG, "startScan");
    }

    /**
     * 确认按钮响应
     * @param psw 密码
     */
    public void confirm(String psw) {
        Log.d(TAG, "confirm->psw:" + psw);
        softApModel.setWifiPassword(psw);
        mView.showWaiting();
        Observable.create(this::connectSocket)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    Disposable d;

                    @Override
                    public void onSubscribe(Disposable d) {
                        this.d = d;
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mView.dismissWaiting();
                        if (integer == ACTION_SUCCESS) {
                            handleSuccess();
                        } else {
                            handleSocketFailue(integer);
                        }
                        d.dispose();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissWaiting();
                        d.dispose();
                    }

                    @Override
                    public void onComplete() {
                        mView.dismissWaiting();
                        d.dispose();
                    }
                });
    }

    /**
     * 与设备建立Socket连接
     * @param emitter 事件发射器
     */
    private void connectSocket(ObservableEmitter<Integer> emitter) {
        softApModel.connectSocket(new SoftApNewModel.SocketListener() {
            @Override
            public void onSuccess() {
                emitter.onNext(ACTION_SUCCESS);
            }

            @Override
            public void onFailure(int errorCode) {
                Log.d(TAG, "connectDevice->onFailure:" + errorCode);
                emitter.onNext(errorCode);
            }
        });
    }

    /**
     * 读取Sn码
     * @param emitter 事件发射器
     */
    private void getSn(ObservableEmitter<Integer> emitter) {
        softApModel.getSn(new SoftApNewModel.ReadSnListener() {
            @Override
            public void onSuccess() {
                emitter.onNext(ACTION_SUCCESS);
            }

            @Override
            public void onFailure(int errorCode) {
                Log.d(TAG, "getSn->onFailure:" + errorCode);
                emitter.onNext(errorCode);
            }
        });
    }

    /**
     * WIFI设置页面返回后续动作
     */
    public void afterSetting() {
        if (!isInit) {
            isInit = true;
            scan();
            return;
        }
        if (getMac) {
            mView.showWaiting();
            Observable.create(this::getSn)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Integer>() {
                        Disposable d;

                        @Override
                        public void onSubscribe(Disposable d) {
                            this.d = d;
                        }

                        @Override
                        public void onNext(Integer integer) {
                            mView.dismissWaiting();
                            if (integer == ACTION_SUCCESS) {
                                handleSuccess();
                            } else {
                                handleGetSnFailue(integer);
                            }
                            d.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissWaiting();
                            d.dispose();
                        }

                        @Override
                        public void onComplete() {
                            mView.dismissWaiting();
                            d.dispose();
                        }
                    });
        }
    }

    /**
     * 处理成功事件
     */
    private void handleSuccess() {
        if (getMac) {
            isSuccess = true;
            GlobalCache.setConnectSocket(false);
            mView.showDialog(R.string.softap_tip1_dialog_success_all, R.string.softap_tip2_dialog_success_all);
        } else {
            getMac = true;
            mView.setSettingFlag();
            mView.showDialog(R.string.softap_tip1_dialog_success_wifi, R.string.softap_tip4_dialog_success_wifi);
        }
    }

    /**
     * 设置ScanResult
     * @param scanResult ScanResult对象
     */
    public void setScanResult(ScanResult scanResult) {
        softApModel.setWifiScanResult(scanResult);
    }

    /**
     * 检查是否配网成功
     */
    public void checkSuccess() {
        if (isSuccess) {
            mView.onFinish();
        }
    }

    /**
     * 处理扫描失败事件
     * @param errorCode 错误码
     */
    private void handleScanFailue(int errorCode) {
        switch (errorCode) {
            case SCAN_AP_TIMEOUT:
                Log.d(TAG, "handleScanFailue:time out");
                break;
            case ERROR_WIFI_DISABLED:
                mView.showDialog(R.string.softap_tip1_dialog_failure_scan, R.string.softap_tip2_dialog_failure_scan);
                break;
        }
    }

    /**
     * 处理与设备建立Socket连接失败事件
     * @param errorCode 错误码
     */
    private void handleSocketFailue(int errorCode) {
        Log.d(TAG, "handleSocketFailue:" + errorCode);
        getMac = false;
        switch (errorCode) {
            case ERROR_WIFI_DISABLED:
                mView.showDialog(R.string.softap_tip1_dialog_failure_wifi, R.string.softap_tip2_dialog_failure_scan);
                break;
            case CONNECT_SOCKET_TIMEOUT:
            case ERROR_SOCKET_NULL:
            case ERROR_SOCKET_FAILED:
                mView.showDialog(R.string.softap_tip1_dialog_failure_wifi, R.string.softap_tip4_dialog_failure_wifi);
                break;
            case ERROR_SSID_NULL:
                mView.showDialog(R.string.softap_tip1_dialog_failure_wifi, R.string.softap_tip3_dialog_failure_wifi);
                break;
            case ERROR_SSID_WRONG:
                mView.setSettingFlag();
                mView.showDialog(R.string.softap_tip1_dialog_failure_wifi, R.string.softap_tip5_dialog_failure_wifi);
                break;
        }
    }

    /**
     * 处理读取Sn码失败事件
     * @param errorCode 错误码
     */
    private void handleGetSnFailue(int errorCode) {
        Log.d(TAG, "handleGetSnFailue:" + errorCode);
        switch (errorCode) {
            case READ_SN_TIMEOUT:
                getMac = false;
                mView.setSettingFlag();
                mView.showDialog(R.string.softap_tip1_dialog_failure_all, R.string.softap_tip4_dialog_failure_all);
                break;
            case ERROR_WIFI_DISABLED:
                mView.showDialog(R.string.softap_tip1_dialog_failure_all, R.string.softap_tip2_dialog_failure_scan);
                break;
        }
    }
}
